package com.onedec.materials.controller;


import com.onedec.materials.entity.OnedecMaterial;
import com.onedec.materials.service.FileService;
import com.onedec.materials.service.FileService;
import com.onedec.materials.service.MaterialService;
import com.onedec.utils.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.GeneratedValue;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author ：
 * @ClassName ：UploadController
 * @date : 2019/4/1 17:47
 * @description : TODO
 */
@RestController
@RequestMapping("/upload")
@Api(tags = "图片上传接口")
public class UploadController {
    @Autowired
    private MaterialService materialService;
    @Autowired
   private FileService fileService;

    @Value("${baseUploadUrl}")
    private String url;

    @PostMapping(value = "/insetMaterisalss")
    @ApiOperation(value = "单个图片上传到七牛云")
    public ResponseEntity uploadImg(@RequestParam(value ="img") MultipartFile upfile, OnedecMaterial material) throws IOException {
        System.out.println(upfile+"______________________"+material);
        Map<String,Object> map = new HashMap<>();
            String fileName = upfile.getOriginalFilename();
            File file = new File(url + fileName);//创建本地文件
        try{
                //将MulitpartFile文件转化为file文件格式
                upfile.transferTo(file);
                Map response = fileService.uploadFile(file);
                Object imageName = response.get("imgName");
                System.out.println("qddyllf7e.bkt.clouddn.com"+imageName);
                material.setMaterialImgUrl("http://qddyllf7e.bkt.clouddn.com/"+imageName);
                materialService.insetMaterial(material);//将实体类存储到数据库
                return ResponseEntity.SUCCESS;
            }catch (Exception e){
                e.printStackTrace();
            }
        return ResponseEntity.ERROR;
        }
    }
